package com.xiaomazi.sms.utils;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @program: llxy-parent
 * @description: 腾讯云发送短信工具类
 * @author: 小马子
 * @create: 2023-02-26 15:59
 **/
public class TxCode {

    private static final String SECRET_ID = "AKIDBAtLWR5SXLs87pHRLyKPDk0yf5E7i25s";
    private static final String SECRET_KEY= "XooXzA4g5D4exzkDPL0OVLuBBuMXRAcn";

    private static final String SMS_SDK_APPID= "1400526378";

    private static final String SIGN_NAME= "小马子学Java";

    private static final String TEMPLATE_ID= "975507";

    private static final String ENDPOINT = "sms.tencentcloudapi.com";

    private static final String REGION = "ap-beijing";

    private static final String PHONE_NUMBER_PREFIX = "+86";

    public static boolean SendCode(String phoneNumber,String code) {
        try {
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(SECRET_ID, SECRET_KEY);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(ENDPOINT);
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, REGION, clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {PHONE_NUMBER_PREFIX+phoneNumber};
            req.setPhoneNumberSet(phoneNumberSet1);

            req.setSmsSdkAppId(SMS_SDK_APPID);
            req.setSignName(SIGN_NAME);
            req.setTemplateId(TEMPLATE_ID);

            String[] templateParamSet1 = {code};
            req.setTemplateParamSet(templateParamSet1);

            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));

            //获取发送状态，若成功则返回true
            for (SendStatus sendStatus : resp.getSendStatusSet()) {
                if ("send success".equals(sendStatus.getMessage()) &&
                        "Ok".equals(sendStatus.getCode())){
                    return true;
                }
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        //若不成，返回false
        return false;
    }
}
